package com.dayaokeji.rhythmschoolstudent.databases.dao;

import android.support.annotation.Nullable;

import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.databases.model.UserInfoModel;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.ArrayList;

/**
 * Created by Gorden on 2017/9/28.
 */

public class UserInfoDao {

    @Nullable
    public static UserInfoModel getUserInfo(String username) {
        try{
            ArrayList<UserInfoModel> userInfos = App.getInstance().getLiteOrm().query(new QueryBuilder<UserInfoModel>(UserInfoModel.class).whereEquals(UserInfoModel.EASE_USER_NAME, username));
            return userInfos.size() > 0 ? userInfos.get(0) : null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void saveUserInfo(com.dayaokeji.server_api.domain.UserInfo userInfo) {
        try{
            UserInfoModel userInfoModel = new UserInfoModel();
            userInfoModel.setUserId(userInfo.getId());
            userInfoModel.setName(userInfo.getName());
            userInfoModel.setAvatarUrl(userInfo.getPictureId() == null? "" : userInfo.getPictureId());
            StringBuilder easeNameBuilder = new StringBuilder();
            easeNameBuilder.append(UserUtils.getUserInfo().getUniversityId());
            easeNameBuilder.append(userInfo.getWorkNo());
            userInfoModel.setEaseUserName(easeNameBuilder.toString());
            if (getUserInfo(easeNameBuilder.toString()) == null) {
                App.getInstance().getLiteOrm().save(userInfoModel);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void delUserInfo() {
        try{
            App.getInstance().getLiteOrm().delete(UserInfoModel.class);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
